package com.tanhua.management.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.Log;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.LogService;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UserStatusApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.UserStatus;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.management.vo.LogVo;
import com.tanhua.management.vo.PageResult;
import com.tanhua.management.vo.UserInfoVo;
import com.tanhua.management.vo.UserVo;
import com.tanhua.management.vo.VideoVo;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ManageService {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserService userService;

    @Reference(version = "1.0.0")
    private UserStatusApi userStatusApi;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Reference(version = "1.0.0")
    private VideoApi videoApi;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;


    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Autowired
    private LogService logService;

    //查询用户信息
    public PageResult queryUsers(Long userId, String nickName, String city, Integer page, Integer pageSize) {
        if (null != userId) {
            IPage<UserInfo> userInfoPage = queryUserListById(userId, page, pageSize);
            List<UserVo> userVos = getUserVos(userInfoPage);
            if (userVos == null) {
                return null;
            }
            return getPageResult(page, pageSize, userInfoPage, userVos);
        }

        if (null != nickName) {
            IPage<UserInfo> userInfoPage = queryUsersListByNickName(nickName, page, pageSize);
            List<UserVo> userVos = getUserVos(userInfoPage);
            if (userVos == null) {
                return null;
            }
            return getPageResult(page, pageSize, userInfoPage, userVos);
        }

        if (null != city) {
            IPage<UserInfo> userInfoPage = queryUsersListByCity(city, page, pageSize);
            List<UserVo> userVos = getUserVos(userInfoPage);
            if (userVos == null) {
                return null;
            }
            return getPageResult(page, pageSize, userInfoPage, userVos);
        }

        //查询当页用户数据
        Page<UserInfo> userInfoPage = new Page<>(page, pageSize);
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        IPage<UserInfo> userInfoIPage = userInfoService.queryByPage(queryWrapper, userInfoPage);
        List<UserVo> userVos = getUserVos(userInfoIPage);
        if (userVos == null) {
            return null;
        }
        return getPageResult(page, pageSize, userInfoPage, userVos);
    }

    private IPage<UserInfo> queryUsersListByCity(String city, Integer page, Integer pageSize) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        Page<UserInfo> userInfoPage = new Page<>(page, pageSize);
        queryWrapper.like("city", city);
        IPage<UserInfo> userInfoIPage = userInfoService.queryByPage(queryWrapper, userInfoPage);

        return userInfoIPage;
    }

    //根据昵称查询
    private IPage<UserInfo> queryUsersListByNickName(String nickName, Integer page, Integer pageSize) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        Page<UserInfo> userInfoPage = new Page<>(page, pageSize);
        queryWrapper.like("nick_name", nickName);
        IPage<UserInfo> userInfoIPage = userInfoService.queryByPage(queryWrapper, userInfoPage);

        return userInfoIPage;
    }

    private PageResult getPageResult(Integer page, Integer pageSize, IPage<UserInfo> userInfoPage, List<UserVo> userVos) {
        PageResult pageResult = new PageResult();
        pageResult.setPages(Long.valueOf(userInfoPage.getPages()).intValue());
        pageResult.setCounts(Long.valueOf(userInfoPage.getTotal()).intValue());
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(userVos);
        return pageResult;
    }

    private List<UserVo> getUserVos(IPage<UserInfo> userInfoPage) {
        List<UserVo> userVos = new ArrayList<>();
        List<UserInfo> records = userInfoPage.getRecords();

        List<Long> ids = new ArrayList<>();
        for (UserInfo record : records) {
            ids.add(record.getUserId());

            UserVo userVo = new UserVo();
            userVo.setId(record.getUserId());
            userVo.setNickname(record.getNickName());
            userVo.setAge(record.getAge());
            userVo.setCity(record.getCity());
            userVo.setLogo(record.getLogo());
            userVo.setSex(record.getSex().getValue() == 1 ? "男" : "女");

            Log log = logService.queryLogByUserId(record.getUserId());
            if (ObjectUtil.isNotEmpty(log)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String format = sdf.format(log.getLogTime());
                userVo.setLastActiveTime(format); //最近活跃时间
            }else {
                userVo.setLastActiveTime("2021-09-19 19:46"); //最近活跃时间
            }

            UserStatus userStatus = userStatusApi.queryUserStatusById(record.getUserId());
            if (ObjectUtil.isEmpty(userStatus)) {
                userVo.setUserStatus("1");
            } else {
                long nowTime = System.currentTimeMillis();
                if (nowTime > userStatus.getUnfreeze()){
                    userVo.setUserStatus("1");
                    unfreeze(userVo.getId().toString(),"...");
                }
                userVo.setUserStatus("2");
            }
            userVos.add(userVo);
        }

        //查询用户手机号
        List<User> userList = userService.queryUserList(ids);
        for (UserVo userVo : userVos) {
            for (User user : userList) {
                if (user.getId().longValue() == userVo.getId().longValue()) {
                    userVo.setMobile(user.getMobile());
                }
            }
        }
        return userVos;
    }

    //根据id搜索
    private IPage<UserInfo> queryUserListById(Long userId, Integer page, Integer pageSize) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        Page<UserInfo> userInfoPage = new Page<>(page, pageSize);
        queryWrapper.like("user_id", userId);
        IPage<UserInfo> userInfoIPage = userInfoService.queryByPage(queryWrapper, userInfoPage);

        return userInfoIPage;
    }

    /**
     * 日志翻页
     * @param sortProp
     * @param page
     * @param pageSize
     * @param sortOrder
     * @param uid
     * @param type
     * @return
     */
    public PageResult querylogs(String sortProp, Integer page, Integer pageSize, String sortOrder, String uid, String type) {
        //封装pageResult对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);//当前页码
        pageResult.setPagesize(pageSize);//页大小
        //查询用户信息
        Page<Log> logPage = new Page<>(page, pageSize);
        QueryWrapper<Log> queryWrapper = new QueryWrapper<Log>().eq("id", uid);
        //查询mysql中的表中数据
        IPage<Log> logIPage = this.logService.queryLogByList(queryWrapper, logPage);
        if (ObjectUtil.isNotEmpty(logIPage)) {
            pageResult.setCounts(Long.valueOf(logIPage.getTotal()).intValue());
            pageResult.setPages(Long.valueOf(logIPage.getPages()).intValue());

            //封装logVo返回
            List<Log> logList = logIPage.getRecords();
            if (ObjectUtil.isNotEmpty(logList)){
                List<LogVo> logVoList = new ArrayList<>();
                for (Log log : logList) {
                    LogVo logVo = new LogVo();
                    logVo.setId(log.getId().intValue());
                    logVo.setLogTime(log.getLogTime());
                    logVo.setPlace(log.getPlace());
                    logVo.setEquipment(log.getEquipment());
                    logVoList.add(logVo);
                }
                if (CollUtil.isNotEmpty(logVoList)){
                    pageResult.setItems(logVoList);
                }
            }
        }
            return pageResult;
    }


    /**
     * 视频记录翻页
     * @param sortProp
     * @param page
     * @param pageSize
     * @param sortOrder
     * @param uid 真正的用户id
     * @return
     */
    public PageResult queryVideosList(String sortProp, Integer page, Integer pageSize, String sortOrder, Integer uid) {
        //通过uid的查询用户信息
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", uid);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);

        //封装pageResult对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);//当前页码
        pageResult.setPagesize(pageSize);//页大小
        List<Video> videoList = videoApi.queryVideosList(uid);
        List<VideoVo> videoVoList = new ArrayList<>();

        //判断videoList是否为空
        if (CollUtil.isEmpty(videoList)) {
            pageResult.setItems(videoVoList);
            return pageResult;
        }
        //videoList不为空，遍历拿出其中信息
        for (Video video : videoList) {
            VideoVo videoVo = new VideoVo();
            videoVo.setId(video.getId().toHexString());
            videoVo.setUserId(userInfo.getUserId().intValue());
            videoVo.setNickname(userInfo.getNickName());
            videoVo.setVideoUrl(video.getVideoUrl());
            videoVo.setCreateDate(video.getCreated().intValue());
            videoVo.setPicUrl(video.getPicUrl());
            videoVo.setReportCount(0);//举报数设置为0
            videoVo.setForwardingCount(0);//转发数设置为0
            //获取点赞数
            String likeKey = "QUANZI_COMMENT_LIKE_" + videoVo.getId();
            String value = redisTemplate.opsForValue().get(likeKey);
            //判断点赞数value是否为空
            if (StringUtils.isEmpty(value)) {
                videoVo.setLikeCount(0);
            } else {
                videoVo.setLikeCount(Integer.parseInt(value));
            }
            videoVo.setCommentCount(0);
            videoVoList.add(videoVo);
        }
        //排序
        Collections.sort(videoVoList, (o1, o2) -> {
            int y = 0;
            switch (sortProp) {
                case "reportCount": {
                    y = o1.getReportCount() - o2.getReportCount();
                    break;
                }
                case "likeCount": {
                    y = o1.getLikeCount() - o2.getLikeCount();
                    break;
                }
                case "commentCount": {
                    y = o1.getCommentCount() - o2.getCommentCount();
                    break;
                }
                case "forwardingCount": {
                    y = o1.getForwardingCount() - o2.getForwardingCount();
                    break;
                }
                case "createDate": {
                }
                default: {
                    y = (int) (o1.getCreateDate() - o2.getCreateDate());
                    break;
                }
            }
            if ("descending".equals(sortOrder)) {
                y = -y;
            }
            return y;
        });
        pageResult.setItems(videoVoList);
        return pageResult;
    }

    //根据id查询详细信息
    public UserInfoVo queryUserInfo(Long userId) {

        User user = userService.queryUserById(userId);
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(userId);

        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setId(userId);
        userInfoVo.setMobile(user.getMobile());
        userInfoVo.setCreated(Long.valueOf(user.getCreated().getTime()).intValue());

        userInfoVo.setNickname(userInfo.getNickName());
        userInfoVo.setTags(userInfo.getTags());
        userInfoVo.setAge(userInfo.getAge());
        userInfoVo.setCity(userInfo.getCity());
        userInfoVo.setSex(userInfo.getSex().toString());
        userInfoVo.setBirthday(userInfo.getBirthday());
        userInfoVo.setCoverPic(userInfo.getCoverPic());
        userInfoVo.setLogo(userInfo.getLogo());
        userInfoVo.setOccupation(userInfo.getIndustry());
        userInfoVo.setIncome(userInfo.getIncome());
        userInfoVo.setMarriage(userInfo.getMarriage());

        Long likeCount = userLikeApi.queryLikeCount(userId);
        userInfoVo.setCountLiked(likeCount.intValue()); //喜欢人数
        Long FanCount = userLikeApi.queryFanCount(userId);
        userInfoVo.setCountBeLiked(FanCount.intValue());   //被喜欢人数
        Long MutualLikeCount = userLikeApi.queryMutualLikeCount(userId);
        userInfoVo.setCountMatching(MutualLikeCount.intValue());  // 配对人数

        Log log = logService.queryLogByUserId(userInfo.getUserId());
        if (ObjectUtil.isNotEmpty(log)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String format = sdf.format(log.getLogTime());
            userInfoVo.setLastActiveTime(format); //最近活跃时间
        }else {
            userInfoVo.setLastActiveTime("2021-09-19 19:46"); //最近活跃时间
        }

        UserLocationVo locationVo = userLocationApi.queryByUserId(userId);
        if (ObjectUtil.isNotEmpty(locationVo)){
            userInfoVo.setLastLoginLocation(locationVo.getAddress());  //  最近登录地
        }else {
            userInfoVo.setLastLoginLocation("合肥");  //  最近登录地
        }

        UserStatus userStatus = userStatusApi.queryUserStatusById(userId);
        if (ObjectUtil.isEmpty(userStatus)) {
            userInfoVo.setUserStatus("1");
        } else {
            long nowTime = System.currentTimeMillis();
            if (nowTime > userStatus.getUnfreeze()) {
                userInfoVo.setUserStatus("1");
                unfreeze(userInfoVo.getId().toString(), "已过冻结时间");
            } else {
                userInfoVo.setUserStatus("2");
            }
        }

        return userInfoVo;
    }

    /**
     * 冻结用户
     *
     * @param userId             用户id
     * @param freezingTime       冻结时间 1->3天  2->7天  3->永久
     * @param freezingRange      冻结范围 1->冻结登录 2->冻结发言 3->冻结发布动态
     * @param reasonsForFreezing 冻结原因
     * @param frozenRemarks      冻结备注
     * @return
     */
    public String freeze(String userId, String freezingTime, String freezingRange, String reasonsForFreezing, String frozenRemarks) {
        if (null == userId || null == freezingTime || null == freezingRange || null == reasonsForFreezing || null == frozenRemarks) {
            return null;
        }

        UserStatus userStatus = new UserStatus();
        userStatus.setId(ObjectId.get());
        userStatus.setUserId(Long.valueOf(userId));
        userStatus.setCreated(System.currentTimeMillis());
        userStatus.setFreezingTime(Integer.valueOf(freezingTime));
        userStatus.setFreezingRange(Integer.valueOf(freezingRange));
        userStatus.setReasonsForFreezing(reasonsForFreezing);
        userStatus.setFrozenRemarks(frozenRemarks);

        Long freezeTime = null;
        switch (freezingTime) {
            case "1":
                freezeTime = userStatus.getCreated() + 86400000L * 3;
                break;
            case "2":
                freezeTime = userStatus.getCreated() + 86400000L * 7;
                break;
            case "3":
                freezeTime = 0L;
                break;
        }

        userStatus.setUnfreeze(freezeTime);

        String key = "USER_FREEZE_RANGE_" + userId;
        Long timeout = userStatus.getUnfreeze() - System.currentTimeMillis();
        timeout = timeout < 0 ? -1 : timeout;
        System.out.println("timeout = " + timeout);
        redisTemplate.opsForValue().set(key, userStatus.getFreezingRange().toString(), timeout, TimeUnit.MILLISECONDS);

        Long expire = redisTemplate.opsForValue().getOperations().getExpire(key);
        System.out.println(expire);

        return userStatusApi.saveUserStatus(userStatus).toString();
    }

    //用户解冻
    public Boolean unfreeze(String userId, String reasonsForThawing) {
        if (ObjectUtil.isEmpty(userId)) {
            return false;
        }

        if (!redisTemplate.hasKey("USER_FREEZE_RANGE_" + userId)) {
            return false;
        }

        Boolean bool = userStatusApi.delUserStatus(Long.valueOf(userId));
        if (bool) {
            Boolean delete = redisTemplate.delete("USER_FREEZE_RANGE_" + userId);
            return delete;
        }

        return false;
    }
}
